<template>
    <div class="dataView">
        <div class="header">
            <!-- <div class="toLogin" @click="toLogin" title="退出登录">
                <el-icon color="#666" style="font-size: 24px;">
                    <User />
                </el-icon>
            </div> -->
            <div class="companyName">污泥转运跟踪平台</div>
            <div class="userInfo">
                <div
                    class=""
                    @click="toMain"
                >
                    <div style="
                            line-height: 50px;
                            width: auto;
                            white-space: nowrap;
                            margin-right: 10px;
                            font-size: 14px;
                            color: #fff;
                        ">
                        你好, {{ realName }}
                    </div>
                </div>
                <div
                    class="toHome"
                    @click="openMsgdrawer"
                >
                    <el-tooltip
                        class="box-item"
                        content="消息"
                        effect="light"
                        placement="bottom"
                    >
                        <el-icon
                            color="#fff"
                            style="font-size: 24px"
                        >
                            <Bell />
                        </el-icon>
                    </el-tooltip>
                    <span></span>
                </div>
                <div
                    class="toHome"
                    @click="toLogin"
                >
                    <el-tooltip
                        class="box-item"
                        content="退出"
                        effect="light"
                        placement="bottom"
                    >
                        <el-icon
                            color="#fff"
                            style="font-size: 24px"
                        >
                            <SwitchButton />
                        </el-icon>
                    </el-tooltip>
                </div>
            </div>
        </div>
        <div
            class="dataContain"
            :style="{ height: hHeight - 50 + 'px' }"
        >
            <div class="menuList">
                <el-scrollbar style="background: #fff">
                    <el-menu
                        :default-active="defaultActive"
                        class="el-menu-vertical-demo"
                        style="border-right: none"
                        :default-openeds="['345', '3','4','5']"
                    >
                        <el-menu-item
                            @click="toHome"
                            :index="'0'"
                        >
                            <el-icon
                                class="elIcon"
                                :size="20"
                            >
                                <Platform />
                            </el-icon>
                            <span>首页</span>
                        </el-menu-item>
                        <el-menu-item
                            @click="toTransferRecord"
                            :index="'1'"
                        >
                            <el-icon
                                class="elIcon"
                                :size="20"
                            >
                                <Guide />
                            </el-icon>
                            <span>转运记录</span>
                        </el-menu-item>
                        <el-menu-item
                            @click="toInspectionRecord"
                            :index="'7'"
                            v-show="authInspection"
                        >
                            <el-icon
                                class="elIcon"
                                :size="20"
                            >
                                <Promotion />
                            </el-icon>
                            <span>巡查记录</span>
                        </el-menu-item>
                        <el-menu-item
                            @click="toExportRecord"
                            :index="'8'"
                        >
                            <el-icon
                                class="elIcon"
                                :size="20"
                            >
                                <Download />
                            </el-icon>
                            <span>导出记录</span>
                        </el-menu-item>
                        <el-menu-item
                            @click="toTransferSetting"
                            :index="'2'"
                        >
                            <el-icon
                                class="elIcon"
                                :size="20"
                            >
                                <Tools />
                            </el-icon>
                            <span>转运设置</span>
                        </el-menu-item>
                        <el-menu-item
                            @click="toPersonnelVehicle"
                            :index="'3'"
                        >
                            <el-icon
                                class="elIcon"
                                :size="20"
                            >
                                <Operation />
                            </el-icon>
                            <span>人员车辆</span>
                        </el-menu-item>
                        <el-sub-menu index="345">
                            <template #title>
                                <el-icon
                                    class="elIcon"
                                    :size="20"
                                >
                                    <User />
                                </el-icon>
                                <span>用户管理</span>

                            </template>
                            <el-menu-item
                                @click="toOrganizationManagement"
                                :index="'4'"
                            >组织管理</el-menu-item>
                            <el-menu-item
                                @click="toToleManagement"
                                :index="'5'"
                            >权责管理</el-menu-item>
                            <el-menu-item
                                @click="toAccountManagement"
                                :index="'6'"
                            >账号管理</el-menu-item>
                        </el-sub-menu>
                    </el-menu>
                </el-scrollbar>
            </div>
            <el-scrollbar class="containRouter">
                <div class="containRouterBox">
                    <router-view :key="route.path"></router-view>
                </div>
            </el-scrollbar>
        </div>

        <el-drawer
            v-model="msgdrawer"
            title="消息中心"
            size="50%"
        >
            <div class="opts">
                <el-radio-group
                    v-model="searchForm.status"
                    size="default"
                    @change="statusChange"
                >
                    <el-radio-button value="0">未读</el-radio-button>
                    <el-radio-button value="1">已读</el-radio-button>
                </el-radio-group>
                <!-- <div class="btns">
                    <el-button type="primary">标为已读</el-button>
                    <el-button type="danger">删除</el-button>
                </div> -->
            </div>
            <!-- <el-button @click="sendMessage(128)">发送</el-button>
            <el-button @click="speakText">播报</el-button> -->
            <el-table
                :data="tableData"
                style="width: 100%"
                highlight-current-row
                size="default"
            >
                <el-table-column
                    prop="message"
                    label="消息内容"
                >

                    <template #default="scope">

                        <el-tooltip
                            class="box-item"
                            effect="dark"
                            :content="scope.row.message"
                            placement="top-start"
                        >
                            <div class="messageContent">{{ scope.row.message }}</div>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="createTime"
                    label="通知时间"
                    width="140"
                />
                <el-table-column
                    label="操作"
                    width="150"
                    fixed="right"
                >
                    <template #default="scope">
                        <el-popconfirm
                            class="box-item"
                            title="确认标记为已读？"
                            placement="top-end"
                            width="180px"
                            @confirm="handleMark(scope.$index, scope.row)"
                            v-if="searchForm.status == '0'"
                        >
                            <template #reference>
                                <el-button
                                    type="primary"
                                    size="small"
                                >
                                    标记已读
                                </el-button>
                            </template>
                        </el-popconfirm>
                        <el-popconfirm
                            class="box-item"
                            title="确认删除？"
                            placement="top-end"
                            width="180px"
                            @confirm="handleDelete(scope.$index, scope.row)"
                        >
                            <template #reference>
                                <el-button
                                    type="danger"
                                    size="small"
                                    style="margin-left: 4px;"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-model:current-page="searchForm.pageNo"
                v-model:page-size="searchForm.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :page-sizes="[10, 20, 50, 100, 200]"
                :total="total"
                size="small"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                class="equipmentPagination"
            />
        </el-drawer>
        <!-- <div
            class="notification"
            :class="notificationFlag ? 'showNotification' : ''"
        >
            <div class="notification_header">
                <el-icon
                    class="elIcon"
                    :size="20"
                    color="#E6A23C"
                >
                    <WarningFilled />
                </el-icon>
                <span style="margin-left: 6px;">通知</span>
            </div>
            <div class="notification_content">
                {{ textToSpeak }}
            </div>
            <div class="notification_footer">
                <el-button
                    type="primary"
                    @click="allowLoadingMud"
                >允许装泥</el-button>
            </div>
        </div> -->
    </div>
</template>

<script setup>
import loginHttp from "@/https/login.js";
import mainHttp from "@/https/main.js";
import menuHttp from "@/https/menu.js";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import {
    Bell,
    Download,
    Guide,
    Operation,
    Platform,
    Promotion,
    SwitchButton,
    Tools,
    User
} from "@element-plus/icons-vue";
import { ElNotification } from "element-plus";
import { nextTick, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

const isSupervisor = ref(false)
const roleNames = ref(Storage.localGet("roleNames"))
if (roleNames.value.includes('supervisor')) {
    isSupervisor.value = true
}
const authInspection = ref(false)
if (roleNames.value != 'admin') {
    authInspection.value = true
}
const hHeight = ref(0);
const localTypeUnit = ref(Storage.localGet("depId"));
const realName = ref(Storage.localGet("realName"));
const router = useRouter();
const route = useRoute();
const roleKeyList = ref();
const defaultActive = ref();
const msgdrawer = ref(false)
const roleIds = ref(Storage.localGet("roleIds"));
const isAdmin = ref(false);
isAdmin.value = roleIds.value.includes(1);

const getdefaultActive = () => {
    if (route.path) {
        console.log(route.path)
        if ('/home' == route.path) {
            defaultActive.value = '0'
        } else if ('/transferSetting' == route.path) {
            defaultActive.value = '2'
        } else if ('/inspectionRecord' == route.path) {
            defaultActive.value = '7'
        } else if ('/exportRecord' == route.path) {
            defaultActive.value = '8'
        } else if ('/transferRecord' == route.path) {
            defaultActive.value = '1'
        } else if ('/personnelVehicle' == route.path) {
            defaultActive.value = '3'
        } else if ('/user/organizationManagement' == route.path) {
            defaultActive.value = '4'
        } else if ('/user/roleManagement' == route.path) {
            defaultActive.value = '5'
        } else if ('/user/accountManagement' == route.path) {
            defaultActive.value = '6'
        }
    } else {
        defaultActive.value = "0";
    }
    console.log(defaultActive.value, "defaultActive.value");
};
const menuRoleKey = async () => {
    const res = await menuHttp.menuRoleKey({
        roleIdList: roleIds.value.split(','),
    });
    if (res.data.code === 200) {
        Storage.localSet("roleKeyList", res.data.data);
        roleKeyList.value = res.data.data.join(',')
    }
};

const toLogin = async () => {
    const res = await loginHttp.logout();
    if (res) {
        router.replace({ path: "/login" });
    }
};
const toHome = () => {
    router.replace({ path: "/home" })
};
const toTransferSetting = () => {
    router.replace({ path: "/transferSetting" })
};
const toExportRecord = () => {
    router.replace({ path: "/exportRecord" })
};
const toInspectionRecord = () => {
    router.replace({ path: "/inspectionRecord" })
};
const toTransferRecord = () => {
    router.replace({ path: "/transferRecord" })
};
const toPersonnelVehicle = () => {
    router.replace({ path: "/personnelVehicle" })
};
const toOrganizationManagement = () => {
    router.replace({ path: "/user/organizationManagement" })
};
const toToleManagement = () => {
    router.replace({ path: "/user/roleManagement" })
};
const toAccountManagement = () => {
    router.replace({ path: "/user/accountManagement" })
};

const searchForm = ref({
    status: '1',
    pageNo: 1,
    pageSize: 10
})
const tableData = ref([])
const total = ref(0)
const openMsgdrawer = async () => {
    msgdrawer.value = true
    getMsgList()
}
const getMsgList = async () => {
    const res = await mainHttp.messageList(searchForm.value)
    console.log(res, 'res')
    if (res.data.code == 200) {
        tableData.value = res.data.data.records
        total.value = res.data.data.total
    }
}
const handleMark = async (index, row) => {
    row.messageIds = row.id
    const res = await mainHttp.readMessage(row)
    if (res.data.code == 200) {
        getMsgList()
    }
}
const handleDelete = async (index, row) => {
    const res = await mainHttp.deleteMessage(row)
    if (res.data.code == 200) {
        getMsgList()
    }
}
const statusChange = (val) => {

    getMsgList()
}
const handleSizeChange = (val) => {
    searchForm.pageSize = val;
    getMsgList();
}
const handleCurrentChange = (val) => {
    searchForm.pageNo = val;
    getMsgList();
}

const notificationFlag = ref(false)
const textToSpeak = ref('车牌号湘A12345已入场');
const isSpeaking = ref(false);

// 语音合成实例
const synth = window.speechSynthesis;

// 播放语音
const speakText = () => {
    ElNotification({
        title: '消息',
        message: textToSpeak.value,
        type: 'warning',
        duration: 0
    })
    // notificationFlag.value = true
    if (!synth) {
        alert('浏览器不支持语音播报');
        return;
    }

    const utterance = new SpeechSynthesisUtterance(textToSpeak.value.split(''));

    // 配置语音参数
    utterance.lang = 'zh-CN';
    utterance.rate = 1.5;
    utterance.pitch = 0.8;
    utterance.volume = 2;

    // 监听事件
    utterance.onend = () => {
        isSpeaking.value = false;
    };

    console.log(textToSpeak.value, 'textToSpeak')
    isSpeaking.value = true;
    synth.speak(utterance);

}

// 停止语音
const stopSpeech = () => {
    if (synth.speaking) {
        synth.cancel();
        isSpeaking.value = false;
    }
}
const socket = ref(null);
const isConnected = ref(false);
const reconnectAttempts = ref(0);
const maxReconnectAttempts = 5;
const messageQueue = ref([]);
const heartbeatInterval = ref(null);

// 心跳配置
const HEARTBEAT_INTERVAL = 30000; // 30秒
const PONG_TIMEOUT = 10000; // 10秒

// 创建连接
const connect = () => {
    socket.value = new WebSocket("ws://14.103.174.114:18082/ws/voiceBroadcast");

    // 监听连接打开
    socket.value.addEventListener('open', handleOpen);

    // 监听消息接收
    socket.value.addEventListener('message', handleMessage);

    // 监听关闭事件
    socket.value.addEventListener('close', handleClose);

    // 监听错误事件
    socket.value.addEventListener('error', handleError);
};

// 发送消息
const sendMessage = (message) => {
    if (socket.value?.readyState === WebSocket.OPEN) {
        console.log(message)
        // socket.value.send(JSON.stringify(message));
        socket.value.send(message);
    } else {
        console.log(message)
        messageQueue.value.push(message);
    }
};

// 关闭连接
const close = () => {
    socket.value?.close();
};

// 处理连接打开
const handleOpen = () => {
    console.log('WebSocket 已连接');
    isConnected.value = true;
    reconnectAttempts.value = 0;
    // sendQueuedMessages();
    sendMessage(Storage.localGet("userId"));
};

// 处理消息接收
const handleMessage = (event) => {
    try {
        // const data = JSON.parse(event.data);
        console.log('收到消息:', event.data);
        stopSpeech()
        textToSpeak.value = event.data
        speakText()
        // 根据业务需求处理消息
    } catch (error) {
        console.error('消息解析失败:', error);
    }
};

// 处理连接关闭
const handleClose = (event) => {
    console.log('WebSocket 已关闭:', event);
    isConnected.value = false;
    stopHeartbeat();
    scheduleReconnect();
};

// 处理错误
const handleError = (error) => {
    console.error('WebSocket 错误:', error);
    isConnected.value = false;
    socket.value?.close();
};

// 发送队列中的消息
const sendQueuedMessages = () => {
    while (messageQueue.value.length > 0) {
        const message = messageQueue.value.shift();
        if (message) {
            socket.value?.send(JSON.stringify(message));
        }
    }
};

// 心跳检测
const startHeartbeat = () => {
    heartbeatInterval.value = window.setInterval(() => {
        if (isConnected.value) {
            // 检测心跳响应
            const pongTimeout = setTimeout(() => {
                console.warn('未收到心跳响应，尝试重连');
                handleClose();
            }, PONG_TIMEOUT);

            // 清除超时检测
            socket.value?.addEventListener('pong', () => {
                clearTimeout(pongTimeout);
            });
        }
    }, HEARTBEAT_INTERVAL);
};

// 停止心跳检测
const stopHeartbeat = () => {
    if (heartbeatInterval.value) {
        clearInterval(heartbeatInterval.value);
        heartbeatInterval.value = null;
    }
};

// 延迟重连
const scheduleReconnect = () => {
    if (reconnectAttempts.value < maxReconnectAttempts) {
        const delay = Math.min(1000 * 2 ** reconnectAttempts.value, 30000);
        setTimeout(() => {
            reconnectAttempts.value++;
            connect();
        }, delay);
    } else {
        console.error('已达到最大重连次数');
    }
};

onMounted(() => {
    nextTick(() => {
        hHeight.value = document.documentElement.clientHeight;
    });
    // menuRoleKey();
    getdefaultActive();
    connect(); // 组件挂载时建立连接
});
</script>
<style lang="less">
.el-drawer__header {
    margin-bottom: 0 !important;
}
.dataView {
    width: 100%;
    height: 100%;
    background: #f5f6fa;
}

.header {
    background: #409eff;
    height: 50px;
    width: 100%;
    // background: #fff;
    border-bottom: 1px solid #ccc;
    // margin-bottom: 20px;
    box-sizing: border-box;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.16);
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    .toHome {
        box-sizing: border-box;
        width: 40px;
        height: 50px;
        // background: #63b2ee;
        text-align: center;
        z-index: 100;
        cursor: pointer;
        padding-top: 12px;
        position: relative;
        span {
            width: 6px;
            height: 6px;
            border-radius: 3px;
            background: red;
            position: absolute;
            right: 10px;
            top: 10px;
        }
    }
    .companyName {
        color: #fff;
        font-size: 16px;
        line-height: 50px;
        padding-left: 30px;
    }
    .userInfo {
        display: flex;
        flex-direction: row;
        padding-right: 20px;
    }
    .toLogin {
        box-sizing: border-box;
        width: 50px;
        height: 50px;
        // background: #63b2ee;
        text-align: center;
        z-index: 100;
        cursor: pointer;
        padding-top: 12px;
    }
}

.dataContain {
    width: 100%;
    display: flex;
    flex-direction: row;
    background: #f6f8f9;
    .menuList {
        width: 188px;
        height: 100%;
        ul {
            height: 100%;
        }
    }
    .leftNave {
        width: 220px;
        background: #eaedf1;

        ul {
            width: 100%;

            li {
                width: 100%;
                height: 48px;
                line-height: 48px;
                display: flex;
                flex-direction: row;
                align-items: center;
                justify-items: flex-start;
                color: #333;
                font-size: 14px;
                cursor: pointer;

                .elIcon {
                    width: 40px;
                    padding-left: 10px;
                }

                &.act {
                    background: #fff;
                }
            }
        }
    }

    .containRouter {
        width: 100%;
        padding: 10px;
        box-sizing: border-box;
        .containRouterBox {
            width: 100%;
            min-height: 100%;
            // background: #fff;
            padding: 10px;
            box-sizing: border-box;
        }
    }
}
:deep .el-scrollbar__view {
    height: 100% !important;
}
.count {
    width: 20px;
    height: 20px;
    background: red;
    border-radius: 10px;
    text-align: center;
    line-height: 20px;
    color: #fff;
    font-size: 10px;
    margin-left: 10px;
}
.el-menu-item.is-active {
    background: #ecf5ff;
    border-left: 4px solid #409eff;
}
.opts {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}
</style>
<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
}
.messageContent {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.equipmentPagination {
    justify-content: right;
    margin-top: 10px;
}
.notification {
    position: fixed;
    right: -330px;
    bottom: 16px;
    box-sizing: border-box;
    z-index: 2012;
    box-shadow: 0 0 12px rgba(0, 0, 0, 0.12);
    width: 330px;
    padding: 14px 26px 14px 13px;
    background: #fff;
    border-radius: 8px;
}
.notification_header {
    display: flex;
    flex-direction: row;
    align-items: center;
    font-size: 14px;
}
.notification_content {
    font-size: 14px;
    padding: 10px 24px;
    line-height: 2;
}
.notification_footer {
    text-align: right;
}
.showNotification {
    right: 16px;
    transition: right 0.5s ease-in-out;
}
</style>
